package com.bfsuol.common.util;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

public class TreeUtil {
	public static class TreeNode {
		private String id;// ID
		private String text;// 显示内容
		private Collection<TreeNode> children;// 下级

		public String getId() {
			return id;
		}

		public void setId(String id) {
			this.id = id;
		}

		public String getText() {
			return text;
		}

		public void setText(String text) {
			this.text = text;
		}

		public Collection<TreeNode> getChildren() {
			return children;
		}

		public void setChildren(Collection<TreeNode> children) {
			this.children = children;
		}

	}

	/**
	 * 实体类集合转为树结构
	 * 
	 * @param data
	 *            实体类集合
	 * @param id
	 *            树节点值对应的实体类属性名
	 * @param text
	 *            树节点显示内容对应实体类属性名
	 * @param children
	 *            子节点对应实体类属性名
	 * @return 树节点集合
	 */
	public static List<TreeNode> convert(Collection data, String id,
			String text, String children) {
		if (data == null || data.size() == 0 || "".equals(id)
				|| "".equals(text)) {
			return null;
		}
		List<TreeNode> treeNodes = new ArrayList<TreeNode>();
		for (Object obj : data) {
			TreeNode treeNode =convert(obj, id, text, children);
			treeNodes.add(treeNode);
		}
		return treeNodes;
	}

	/**
	 * 实体类集合转为树结构
	 * 
	 * @param obj
	 *            实体类
	 * @param id
	 *            树节点值对应的实体类属性名
	 * @param text
	 *            树节点显示内容对应实体类属性名
	 * @param children
	 *            子节点对应实体类属性名
	 * @return 树节点
	 */
	public static TreeNode convert(Object obj, String id, String text,
			String children) {
		if (obj == null || "".equals(id) || "".equals(text)) {
			return null;
		}
		TreeNode treeNode = new TreeNode();
		try {
			Field idField = obj.getClass().getDeclaredField(id);
			idField.setAccessible(true);
			Field textField = obj.getClass().getDeclaredField(text);
			textField.setAccessible(true);
			Field childrenField = obj.getClass().getDeclaredField(children);
			childrenField.setAccessible(true);
			treeNode.setId(idField.get(obj).toString());
			treeNode.setText(textField.get(obj).toString());
			Object childrenObject = childrenField.get(obj);

			Collection childCollection = (Collection) childrenObject;
			if (childCollection.size() > 0) {
				treeNode.setChildren(convert(childCollection, id, text,
						children));
			}
		} catch (Exception e) {

			e.printStackTrace();
		}
		return treeNode;
	}
}
